package com.stylefeng.guns.core.intercept;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.core.redis.RedisService;
import com.stylefeng.guns.core.result.JsonReturnHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 平台用户拦截器(暂时简单处理，后续可以增加时间以及每次请求变更token等方式控制)
 * @author zcj
 */
@Component
public class PlatformUserInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, token, Authorization, X-Requested-With");

        String requestUri = request.getRequestURI();

       /* if (requestUri.startsWith("/api/pc") && !requestUri.startsWith("/api/pc/unauthorized") && !"OPTIONS".equals(request.getMethod())) {

            String token = request.getHeader("token");
            if(StringUtils.isBlank(token) || redisService.getObj(token) == null){

                PrintWriter out = response.getWriter();
                out.write(JSONObject.toJSONString(JsonReturnHelper.getFailWithError("登录过期，请重新登录！","999999")));
                out.flush();
                out.close();

                return false;
            } else {
                //重新设置一次redis
                redisService.set(token, redisService.getObj(token),60*30); //有效时间30分钟
            }
        }
*/
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
